USE db_World

IF OBJECT_ID('dbo.tbl_Accounts', 'U') IS NULL
BEGIN
	CREATE TABLE tbl_Logs
	(
		log_id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
		log_accountId INT NOT NULL,
		CONSTRAINT log_FK_accountId FOREIGN KEY (log_accountId) REFERENCES tbl_Accounts(account_id),
		log_oldSum MONEY NOT NULL,
		log_newSum MONEY NOT NULL
	)
END
GO

IF OBJECT_ID('trig_onAccountBalanceChange', 'TR') IS NOT NULL
BEGIN
	DROP TRIGGER trig_onAccountBalanceChange	
END
GO

CREATE TRIGGER trig_onAccountBalanceChange
	ON tbl_Accounts
	FOR UPDATE
AS BEGIN
	IF UPDATE (account_balance)
	BEGIN
		INSERT INTO tbl_Logs (log_accountId, log_oldSum, log_newSum)
		SELECT
			d.account_id,
			d.account_balance AS log_oldSum,
			i.account_balance AS log_newSum
		FROM INSERTED i, DELETED d
	END
END
GO